package rs;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.logging.Logger;

import org.nutz.json.Json;
import org.nutz.lang.Files;

import rs.util.FolderListener;
import rs.util.FolderMonitor;
import rs.util.Log;
import rs.util.StringUtil;

public class JobManager {


	
	public static ScheduledThreadPoolExecutor JOB_CENTER = new ScheduledThreadPoolExecutor(5);

	public Runnable work() {
		
		FolderMonitor monitor = new FolderMonitor(Conf.JOB_DESCRIPTION_DIR,
				Conf.JOB_CHECKING_PERIOD_IN_SECOND, new FolderListener() {
					
					// we care.
					public void onFileModified(String absolutePath) {
						//XXX 更新工单描述?
						//TODO 完成更新工单逻辑
					}
					
					public void onFileCreated(String absolutePath) {
						
						onNewJobDesc(absolutePath);
					}
					@Override
					public void afterFirstScan() {
						// TODO Auto-generated method stub
						
					}
				}, true);
		//monitor.run();
		new Thread(monitor).start();
		return monitor;
	}
	
	private void onNewJobDesc(String path){
		//向任务池中申请JobProcessor来执行.
		Logger.getLogger(this.getClass().getName()).info("Add job from " + path);
		//System.out.println("JobManager: find job @ " + path);
		String jobJson = Files.read(path);
		addAJobDesc(jobJson);
		/*
		JobProcessor jobProcessor = new JobProcessor(jobJson);
		JOB_CENTER.scheduleAtFixedRate(jobProcessor, 0, 1, TimeUnit.DAYS);
		*/
	}

	/**
	 * 添加一个job描述
	 * @param jobJson job描述,json格式
	 */
	public void addAJobDesc(String jobJson) {
		JobDesc jobDesc = Json.fromJson(JobDesc.class, jobJson);
		addAJobDesc(jobDesc);
	}

	/**
	 * 添加一个job描述
	 * @param jobDesc job描述
	 */
	public void addAJobDesc(JobDesc jobDesc) {
		if(jobDesc != null && StringUtil.notEmpty(jobDesc.id )){
			synchronized (ProjectManager.class) {
				Log.info("ADDING JOB: " + jobDesc.id);
				ProjectManager.JOB_TYPES.put(jobDesc.id, jobDesc);
			}
		}
	}

	public static void main(String[] args) {
		JobManager j = new JobManager();
		j.work();
	}
}
